package utile

import (
	"context"
	"fmt"
	"github.com/olivere/elastic/v7"
	"logstash/config"
	"logstash/models"
	"strings"
	"time"
)

type Es struct {
	host   string
	client *elastic.Client
}

var es = &Es{}

func GetEsClient() (*Es, error) {
	if es.client == nil {
		conf := config.GetConfig()
		url := fmt.Sprintf("http://%s:%s", conf.Data.Es.Host, conf.Data.Es.Port)
		client, err := elastic.NewClient(elastic.SetSniff(false), elastic.SetURL(url), elastic.SetBasicAuth(conf.Data.Es.Username, conf.Data.Es.Password))
		//client, err := elastic.NewClient(elastic.SetURL("http://127.0.0.1:9200"))
		if err != nil {
			fmt.Printf("failed to connect es ,err: %s\n", err)
			// Handle error
			return nil, err
		}
		es.host = conf.Data.Es.Host
		es.client = client
	}
	//fmt.Println("connect to es success")
	return es, nil
}

func SendData2Es(msgBag *models.MessageBag) error {
	var err error
	if es == nil {
		es, err = GetEsClient()
		if err != nil {
			//logger.Errorf("链接ES失败，err: %v\n", err)
			return err
		}
	}
	_, timestamp := GetTimestamp()
	_, err = es.client.Index().
		//put1, err := es.client.Index().
		Index(msgBag.MsgType).
		Id(timestamp).
		BodyJson(msgBag).
		Do(context.Background())
	if err != nil {
		fmt.Printf("send msg to ES failed，err: %s\n", err)
		return err
	}
	fmt.Println("send msg to ES SUCC")
	//fmt.Printf("es indexed user %s to index %s, type %s\n", put1.Id, put1.Index, put1.Type)
	return nil
}

func GetES() *Es {
	return es
}

func (e *Es) HeartBeat() {
	flag := true
	conf := config.GetConfig()
	for {
		time.Sleep(time.Second * 5)
		if cli, err := GetEsClient(); err != nil {
			fmt.Println("ES [ " + conf.Data.Es.Host + " ] Heart Beat Failed")
			if flag {
				// 发送邮件给管理员，提醒ES挂了
				SendMail2Admin("ES [ "+conf.Data.Es.Host+" ] Heart Beat Failed", err.Error())
			}
			flag = false
		} else {
			//ES配置修改重置client
			if !strings.EqualFold(cli.host, conf.Data.Es.Host) {
				fmt.Printf("ES配置修改,new host: %s, old host: %s \n", conf.Data.Es.Host, cli.host)
				cli.client = nil
			}
			fmt.Println("ES [ " + conf.Data.Es.Host + " ] Heart Beat SUCC")
			if !flag {
				// 发送邮件给管理员，提醒ES启动了
				SendMail2Admin("ES [ "+conf.Data.Es.Host+" ] Heart Beat SUCC", "ES重新检测SUCC")
			}
			flag = true
		}
	}
}
